using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;

using ExpertPdf.HtmlToPdf;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        lblConvertMessage.Visible = false;

        if (!IsPostBack)
        {
            LoadImageFormats();
            LoadPDFFormats();
            LoadPageOrientations();
            LoadColors();
            LoadCompressionLevels();
            LoadPdfSubsets();
        }
    }

    private void LoadImageFormats()
    {
        string[] imageFormats = Enum.GetNames(typeof(RenderImageFormat));
        ddlImageFormat.DataSource = imageFormats;
        ddlImageFormat.DataBind();
        ddlImageFormat.SelectedValue = RenderImageFormat.Jpeg.ToString();
    }

    private void LoadCompressionLevels()
    {
        string[] pdfCompressionLevels = Enum.GetNames(typeof(PdfCompressionLevel));
        ddlCompressionLevel.DataSource = pdfCompressionLevels;
        ddlCompressionLevel.DataBind();
        ddlCompressionLevel.SelectedValue = PdfCompressionLevel.Normal.ToString();
    }

    private void LoadPageOrientations()
    {
        string[] pdfPageOrientations = Enum.GetNames(typeof(PDFPageOrientation));
        ddlPageOrientation.DataSource = pdfPageOrientations;
        ddlPageOrientation.DataBind();
        ddlPageOrientation.SelectedValue = PDFPageOrientation.Portrait.ToString();
    }

    private void LoadPDFFormats()
    {
        string[] pdfFormats = Enum.GetNames(typeof(PdfPageSize));
        ddlPDFPageFormat.DataSource = pdfFormats;
        ddlPDFPageFormat.DataBind();
        ddlPDFPageFormat.SelectedValue = PdfPageSize.A4.ToString();
    }

    private void LoadColors()
    {
        string[] colors = Enum.GetNames(typeof(KnownColor));

        ddlHeaderColor.DataSource = colors;
        ddlHeaderColor.DataBind();
        ddlHeaderColor.SelectedValue = KnownColor.Black.ToString();

        ddlFooterTextColor.DataSource = colors;
        ddlFooterTextColor.DataBind();
        ddlFooterTextColor.SelectedValue = KnownColor.Black.ToString();
    }

    private string[] pdfStandards = { "PDF", "PDF/A", "PDF/X", "PDF/SiqQA", "PDF/SiqQB" };
    private PdfStandardSubset GetPdfStandard(string standardName)
    {
        switch (standardName)
        {
            case "PDF":
                return PdfStandardSubset.Full;
            case "PDF/A":
                return PdfStandardSubset.Pdf_A_1b;
            case "PDF/X":
                return PdfStandardSubset.Pdf_X_1a;
            case "PDF/SiqQA":
                return PdfStandardSubset.Pdf_SiqQ_a;
            case "PDF/SiqQB":
                return PdfStandardSubset.Pdf_SiqQ_b;
            default:
                return PdfStandardSubset.Full;

        }
    }

    private void LoadPdfSubsets()
    {
        ddlPdfSubset.DataSource = pdfStandards;
        ddlPdfSubset.DataBind();
        ddlPdfSubset.SelectedValue = "PDF";
    }

    /// <summary>
    /// Create a PdfConverter object
    /// </summary>
    /// <returns></returns>
    private PdfConverter GetPdfConverter()
    {
        PdfConverter pdfConverter = new PdfConverter();

        //pdfConverter.LicenseKey = "put your license key here";

        // set the HTML page width in pixels
        // the default value is 1024 pixels
        if (radioCustomWebPageSize.Checked)
        {
            pdfConverter.PageWidth = int.Parse(textBoxCustomWebPageWidth.Text.Trim());
        }
        else
        {
            pdfConverter.PageWidth = 0; // autodetect the HTML page width
        }

        // set if the generated PDF contains selectable text or an embedded image - default value is true
        pdfConverter.PdfDocumentOptions.GenerateSelectablePdf = cbGenerateSelectablePdf.Checked;

        //set the PDF page size 
        pdfConverter.PdfDocumentOptions.PdfPageSize = (PdfPageSize)Enum.Parse(typeof(PdfPageSize), ddlPDFPageFormat.SelectedValue);
        // set the PDF compression level
        pdfConverter.PdfDocumentOptions.PdfCompressionLevel = (PdfCompressionLevel)Enum.Parse(typeof(PdfCompressionLevel), ddlCompressionLevel.SelectedValue);
        // set the PDF page orientation (portrait or landscape)
        pdfConverter.PdfDocumentOptions.PdfPageOrientation = (PDFPageOrientation)Enum.Parse(typeof(PDFPageOrientation), ddlPageOrientation.SelectedValue.ToString());
        //set the PDF standard used to generate the PDF document
        pdfConverter.PdfStandardSubset = GetPdfStandard(ddlPdfSubset.SelectedItem.ToString());
        // show or hide header and footer
        pdfConverter.PdfDocumentOptions.ShowHeader = cbShowheader.Checked;
        pdfConverter.PdfDocumentOptions.ShowFooter = cbShowFooter.Checked;
        //set the PDF document margins
        pdfConverter.PdfDocumentOptions.LeftMargin = int.Parse(textBoxLeftMargin.Text.Trim());
        pdfConverter.PdfDocumentOptions.RightMargin = int.Parse(textBoxRightMargin.Text.Trim());
        pdfConverter.PdfDocumentOptions.TopMargin = int.Parse(textBoxTopMargin.Text.Trim());
        pdfConverter.PdfDocumentOptions.BottomMargin = int.Parse(textBoxBottomMargin.Text.Trim());
        // set if the HTTP links are enabled in the generated PDF
        pdfConverter.PdfDocumentOptions.LiveUrlsEnabled = cbLiveLinksEnabled.Checked;
        // set if the HTML content is resized if necessary to fit the PDF page width - default is true
        pdfConverter.PdfDocumentOptions.FitWidth = cbFitWidth.Checked;
        // set if the PDF page should be automatically resized to the size of the HTML content when FitWidth is false
        pdfConverter.PdfDocumentOptions.AutoSizePdfPage = true;
        // embed the true type fonts in the generated PDF document
        pdfConverter.PdfDocumentOptions.EmbedFonts = cbEmbedFonts.Checked;
        // compress the images in PDF with JPEG to reduce the PDF document size - default is true
        pdfConverter.PdfDocumentOptions.JpegCompressionEnabled = cbJpegCompression.Checked;
        // set if the JavaScript is enabled during conversion 
        pdfConverter.ScriptsEnabled = pdfConverter.ScriptsEnabledInImage = cbScriptsEnabled.Checked;

        // set if the converter should try to avoid breaking the images between PDF pages
        pdfConverter.AvoidImageBreak = cbAvoidImageBreak.Checked;

        pdfConverter.PdfHeaderOptions.HeaderText = textBoxHeaderText.Text;
        pdfConverter.PdfHeaderOptions.HeaderTextColor = Color.FromKnownColor((KnownColor)Enum.Parse(typeof(KnownColor), ddlHeaderColor.SelectedValue));
        pdfConverter.PdfHeaderOptions.HeaderSubtitleText = textBoxHeaderSubtitle.Text;
        pdfConverter.PdfHeaderOptions.DrawHeaderLine = cbDrawHeaderLine.Checked;
        pdfConverter.PdfHeaderOptions.HeaderHeight = 50;

        pdfConverter.PdfFooterOptions.FooterText = textBoxFooterText.Text;
        pdfConverter.PdfFooterOptions.FooterTextColor = Color.FromKnownColor((KnownColor)Enum.Parse(typeof(KnownColor), ddlFooterTextColor.SelectedValue));
        pdfConverter.PdfFooterOptions.DrawFooterLine = cbDrawFooterLine.Checked;
        pdfConverter.PdfFooterOptions.PageNumberText = textBoxPageNmberText.Text;
        pdfConverter.PdfFooterOptions.ShowPageNumber = cbShowPageNumber.Checked;
        pdfConverter.PdfFooterOptions.FooterHeight = 50;

        pdfConverter.PdfBookmarkOptions.TagNames = cbBookmarks.Checked ? new string[] { "h1", "h2" } : null;

        return pdfConverter;
    }

    private ImgConverter GetImgConverter()
    {
        ImgConverter imgConverter = new ImgConverter();

        //imgConverter.LicenseKey = "put your license key here";

        // set common properties
        if (radioCustomWebPageSize.Checked)
        {
            imgConverter.PageWidth = int.Parse(textBoxCustomWebPageWidth.Text.Trim());
        }
        imgConverter.ScriptsEnabled = cbScriptsEnabled.Checked;

        return imgConverter;
    }

    private System.Drawing.Imaging.ImageFormat GetImageFormat(RenderImageFormat format)
    {
        switch (format)
        {
            case RenderImageFormat.Bmp:
                return System.Drawing.Imaging.ImageFormat.Bmp;
            case RenderImageFormat.Gif:
                return System.Drawing.Imaging.ImageFormat.Gif;
            case RenderImageFormat.Jpeg:
                return System.Drawing.Imaging.ImageFormat.Jpeg;
            case RenderImageFormat.Png:
                return System.Drawing.Imaging.ImageFormat.Png;
            case RenderImageFormat.Tiff:
                return System.Drawing.Imaging.ImageFormat.Tiff;
            default:
                return System.Drawing.Imaging.ImageFormat.Bmp;
        }
    }

    protected void btnConvert_Click(object sender, EventArgs e)
    {
        lblConvertMessage.Visible = false;

        if (!Page.IsValid)
            return;

        string urlToConvert = textBoxWebPageURL.Text.Trim();

        string downloadName = "Report";
        byte[] downloadBytes = null;

        if (radioConvertToPDF.Checked || radioConvertToSelectableText.Checked)
        {
            downloadName += ".pdf";
            PdfConverter pdfConverter = GetPdfConverter();
            downloadBytes = pdfConverter.GetPdfBytesFromUrl(urlToConvert);
        }
        else
        {
            downloadName += "." + ddlImageFormat.SelectedValue;
            ImgConverter imgConverter = GetImgConverter();
            downloadBytes = imgConverter.GetImageFromUrlBytes(urlToConvert, GetImageFormat((RenderImageFormat)Enum.Parse(typeof(RenderImageFormat), ddlImageFormat.SelectedValue)));
        }

        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
        response.Clear();
        response.AddHeader("Content-Type", "binary/octet-stream");
        response.AddHeader("Content-Disposition",
            "attachment; filename=" + downloadName + "; size=" + downloadBytes.Length.ToString());
        response.Flush();
        response.BinaryWrite(downloadBytes);
        response.Flush();
        response.End();
    }
    protected void lnkBtnSettings_Click(object sender, EventArgs e)
    {
        if (!Page.IsValid)
            return;

        if (pnlRenderMoreOptions.Visible)
        {
            pnlRenderMoreOptions.Visible = false;
            lnkBtnSettings.Text = "More Converter Settings >>";
        }
        else
        {
            pnlRenderMoreOptions.Visible = true;
            lnkBtnSettings.Text = "<< Hide Settings";
        }
    }
    protected void radioAutodetectWebPageSize_CheckedChanged(object sender, EventArgs e)
    {
        pnlCustomPageSize.Visible = !((RadioButton)sender).Checked;
    }
    protected void radioCustomWebPageSize_CheckedChanged(object sender, EventArgs e)
    {
        pnlCustomPageSize.Visible = ((RadioButton)sender).Checked;
    }
    protected void radioConvertToPDF_CheckedChanged(object sender, EventArgs e)
    {
        pnlImageRenderOptions.Visible = !((RadioButton)sender).Checked;
        pnlPDFRenderOptions.Visible = ((RadioButton)sender).Checked;
        cbGenerateSelectablePdf.Checked = false;
        cbEmbedFonts.Visible = radioConvertToSelectableText.Checked;
        cbJpegCompression.Visible = cbFitWidth.Visible = cbLiveLinksEnabled.Visible = cbBookmarks.Visible = !radioConvertToImage.Checked;
    }
    protected void radioConvertToImage_CheckedChanged(object sender, EventArgs e)
    {
        pnlImageRenderOptions.Visible = ((RadioButton)sender).Checked;
        pnlPDFRenderOptions.Visible = !((RadioButton)sender).Checked;
        cbEmbedFonts.Visible = radioConvertToSelectableText.Checked;
        cbJpegCompression.Visible = cbFitWidth.Visible = cbLiveLinksEnabled.Visible = cbBookmarks.Visible = !radioConvertToImage.Checked;
    }
    protected void cbShowheader_CheckedChanged(object sender, EventArgs e)
    {
        pnlPDFHeaderOptions.Visible = ((CheckBox)sender).Checked;
    }
    protected void cbShowFooter_CheckedChanged(object sender, EventArgs e)
    {
        pnlPDFFooterOptions.Visible = ((CheckBox)sender).Checked;
    }
    protected void cvCustomPageWidth_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = true;
        int width = 0;
        try
        {
            width = int.Parse(textBoxCustomWebPageWidth.Text.Trim());
        }
        catch
        {
            args.IsValid = false;
            return;
        }
        args.IsValid = width >= 0;
    }
    protected void cvLeftMargin_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = true;
        int width = 0;
        try
        {
            width = int.Parse(textBoxLeftMargin.Text.Trim());
        }
        catch
        {
            args.IsValid = false;
            return;
        }
        args.IsValid = width >= 0;
    }
    protected void cvRightMargin_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = true;
        int width = 0;
        try
        {
            width = int.Parse(textBoxRightMargin.Text.Trim());
        }
        catch
        {
            args.IsValid = false;
            return;
        }
        args.IsValid = width >= 0;
    }
    protected void cvTopMargin_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = true;
        int width = 0;
        try
        {
            width = int.Parse(textBoxTopMargin.Text.Trim());
        }
        catch
        {
            args.IsValid = false;
            return;
        }
        args.IsValid = width >= 0;
    }
    protected void cvBottomMargin_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = true;
        int width = 0;
        try
        {
            width = int.Parse(textBoxBottomMargin.Text.Trim());
        }
        catch
        {
            args.IsValid = false;
            return;
        }
        args.IsValid = width >= 0;
    }
    protected void radioConvertToSelectableText_CheckedChanged(object sender, EventArgs e)
    {
        pnlImageRenderOptions.Visible = !((RadioButton)sender).Checked;
        pnlPDFRenderOptions.Visible = ((RadioButton)sender).Checked;
        cbGenerateSelectablePdf.Checked = true;
        cbEmbedFonts.Visible = radioConvertToSelectableText.Checked;
        cbJpegCompression.Visible = cbFitWidth.Visible = cbLiveLinksEnabled.Visible = cbBookmarks.Visible = !radioConvertToImage.Checked;
    }
}
